var success=jobIndex=failed=start=0,
http = require('http'),
tmo=1000,nodes=15,
opt=require('./config').onekey,
os = require('os'),
countdown=require('./countdown'),
sdc = require('sdc-clients'),
workflow=require('./config').poc.workflow,
vmapi = new sdc.VMAPI(require('./config').poc.vmapi),
cnapi = new sdc.CNAPI(require('./config').poc.cnapi)/*,
 rl = require('readline').createInterface({
	input: process.stdin,
	output: process.stdout
}) */
						
//console.log('配置：',opt,'\n')
//rl.question('确定要继续吗？回车继续，任意键+回车退出！！！\n', function(answer){
//	if(answer)process.exit(1)
//	else{
//		rl.close()
		start=new Date()
		serializeCreate()
//	}
//})
function(ip,cb){
	var Client = require('ssh2').Client
	var conn = new Client()
	conn.on('ready',function(){
		var data='';
		conn.exec('uptime', function(err, stream) {
			stream.on('close', function(code, signal) {
				cb(err||data)
			}).on('data', function(data) {
			  data=data
			}).stderr.on('data', function(data) {
			  data=data
			})
		})
	}).connect({
	  host: ip,
	  port: 22,
	  username: 'root',
	  privateKey: require('fs').readFileSync('./wangjh')
	})
}
function serializeCreate(){
	var begin=new Date()
	vmapi.createVm(opt,function(err, obj) {
		var end=new Date(),presentCount=++jobIndex
		if(presentCount<nodes)cnapi.getServer(opt.server_uuid,function(err, server) {
			if(server.memory_available_bytes/server.memory_total_bytes>0.15)setTimeout(serializeCreate,tmo)
		})
		if(err)errs(err,presentCount)
		else{
			console.log('\n序列化创建第'+presentCount+'项任务，api响应时间：',countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),'('+begin.getTime()+'~'+end.getTime()+')')
			setTimeout(function(){cometState(obj,begin)},tmo)
		}
	})
}
function createVM(){
	var begin=new Date()
	vmapi.createVm(opt,function(err, obj) {
		var end=new Date(),presentCount=++jobIndex
		if(err)errs(err,presentCount)
		else{
			console.log('\n序列化创建第'+presentCount+'项任务，api响应时间：',countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),
				'('+begin.getTime()+'~'+end.getTime()+')')
			setTimeout(function(){cometState(obj,begin)},tmo)
		}
	})
}
function errs(err,index){
	if(err.body&&err.body.errors)
		for(var e in err.body.errors)
			console.error('!!!!!!!!!!第'+index+'项任务无法创建',err.body.errors[e])
	else console.error('!!!!!!!!!!第'+index+'项任务无法创建',err)
}
function cometState(obj,begin){
	var options = {
		hostname: workflow, 
		path: '/jobs/'+obj.job_uuid,
		method: 'GET',
		headers: {"Accept": "application/json"}
	};
	var req = http.request(options, function (res) {
		var body = '';
		res.setEncoding('utf8');
		res.on('data',function(d){
			body += d;
		}).on('end', function(){
			var jobState=JSON.parse(body).execution
			if(jobState==="succeeded"||jobState==="failed"||jobState==="canceled"){
				var end=new Date()
				vmapi.getVm({uuid:obj.vm_uuid},function(err, vm){
						if(vm.state=='running'){
							ssh2(vm.nics[0].ip,function(er,uptime){
								if(!er&&uptime){
									console.log('\n有%s台主机创建成功，耗时:%s,IP:%s,jobState:%s,vmState:%s\nuptime:%s',++success,countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),vm.nics[0].ip,jobState,vm.state,uptime,'('+begin.getTime()+'~'+end.getTime()+')')
								}else{
									console.error('\n!!!!!!!!!!有%s台主机创建失败，耗时:%s,jobState:%s,vmState:%s',++failed,countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),jobState,vm.state,JSON.parse(body).chain_results.pop().error.message||JSON.parse(body).chain_results.pop().error||er,'('+begin.getTime()+'~'+end.getTime()+')')
								}
							})
						}else{
							console.error('\n!!!!!!!!!!有%s台主机创建失败，耗时:%s,jobState:%s,vmState:%s',++failed,countdown(end,begin,countdown.SECONDS | countdown.MILLISECONDS).toString(),jobState,vm.state,err||JSON.parse(body).chain_results.pop().error.message||JSON.parse(body).chain_results.pop().error,'('+begin.getTime()+'~'+end.getTime()+')')
						}
								cnapi.getServer(opt.server_uuid,function(err, servercn) {
									if(servercn.memory_available_bytes/servercn.memory_total_bytes>0.15){
										setTimeout(createVM,tmo)
										if(nodes<15)setTimeout(createVM,tmo)
									}else{
										--nodes
										if(jobIndex===(success+failed)){
											console.log('\n\n~~~~~~~~程序结束，执行'+jobIndex+'次，成功'+success+'台,失败'+failed+'台，总耗时：',countdown(end,start,countdown.SECONDS | countdown.MILLISECONDS).toString(),'('+start.getTime()+'~'+end.getTime()+')\n\n')
											console.log('CN剩余内存%s%',servercn.memory_available_bytes/servercn.memory_total_bytes*100)
											console.log('程序运行环境内存剩余%s%,时间计算误差%sms！！！！！',os.freemem()/os.totalmem()*100,tmo)
											//process.exit(1)
										}
									}
								})
				})
			}else{
				if(
					os.freemem()/os.totalmem()<0.20||
					process.memoryUsage().heapUsed/process.memoryUsage().heapTotal>0.80
				)tmo=tmo+500
				else if(
					os.freemem()/os.totalmem()>0.40&&
					process.memoryUsage().heapUsed/process.memoryUsage().heapTotal<0.60&&
					tmo!=500
				)tmo=tmo-500
				setTimeout(function(){cometState(obj,begin)},tmo)
			}
		})
	}).on('error', function(e) {
		console.error('\n!!!!!!!!!!查询'+obj.job_uuid+'任务进度异常：',e.message);
	})
	req.end();
}